package pl.edu.agh.mguesser.playlist.parser;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import pl.edu.agh.mguesser.playlist.Playlist;
import pl.edu.agh.mguesser.playlist.PlaylistImpl;

/**
 * @author keiran
 */
public class M3UPlaylistParser implements PlaylistParser {

    @Override
    public Playlist parse(Path path) throws PlaylistParserException {
        try(Scanner scanner = new Scanner(path)) {
            List<Path> songs = new ArrayList<>();
            
            while(scanner.hasNextLine()) {
                String line = scanner.nextLine();
                
                // skip empty lines and special sections
                if(!line.matches("\\s*") && !line.startsWith("#")) {
                    Path converted = Paths.get(line);
                    
                    if(converted.isAbsolute()) {
                        songs.add(converted);
                    } else {
                        songs.add(path.getParent().resolve(converted));
                    }
                } 
            }
            
            return new PlaylistImpl(songs);
            
        } catch(IOException ex) {
            throw new PlaylistParserException(ex);
            
        }
    }
    
}
